//
//  UserAccountViewModel.swift
//  Sina
//
//  Created by 王杰 on 15/11/10.
//  Copyright © 2015年 王杰. All rights reserved.
//

import UIKit
import AFNetworking
class UserAccountViewModel: NSObject {

    //增加一个account属性
    var account:UserAccount?
    
    //增加一个用户是否登录属性
    var userLogin:Bool {
    
    return account?.access_token != nil
    
    }
    var token:String? {
    
    return account?.access_token
    }
    
    var headUrl: NSURL? {
    
    return NSURL(string: (account?.avatar_large ?? ""))
        
    }
    
    var userName :String? {
    
    return account?.name
        
    }
    //在init 获取用户账户
   override init() {
       account = UserAccount.loadAccount()
    
    }
    
    func loadAccessToken(code:String,finished:(error:NSError?) ->()) {
        //获取授权
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        //POST 请求
        NetworkTools.sharedTools.requestJsonDict(.POST, urlString: urlString, parmaters: parameters) { (result, error) -> () in
            
            if error != nil {
            
            print("================")
                print(error)
                finished(error: error)
            
                return
            }
            print(result)
            let account = UserAccount(dict: result!)
            self.loadUserInfo(account, finished: finished)
        }
    }
    
    //加载用户信息
   private func loadUserInfo(account:UserAccount,finished:(error:NSError?) ->()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parmaters = ["access_token":account.access_token!,"uid":account.uid!]
    //GET 请求
    NetworkTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parmaters: parmaters) { (result, error) -> () in
        if error != nil {
            finished(error: error)
            return
        }
        //请求用户信息
        account.avatar_large = result!["avatar_large"] as? String
        account.name = result!["name"] as? String
        
        account.saveAccount()
        
        ///执行闭包
        finished(error: nil)
        }
  
    }
}
